package com.smilive.start.netty.netty;

import io.netty.channel.EventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @program: netty
 * @Date: 2022-01-05 15:08
 * @Author: smilive
 * @Description:
 */
@Slf4j
public class NettyFuture {

    public static void main(String[] args) throws ExecutionException, InterruptedException, IOException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        // 获得 EventLoop 对象
        EventLoop eventLoop = group.next();
        Future<String> future = eventLoop.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                TimeUnit.SECONDS.sleep(1);
                return "任务线程名称: "+Thread.currentThread().getName();
            }
        });
        //主线程获取结果
        //阻塞获取返回结果
        log.debug("结果:{}",future.get());
        //获取任务结果，非阻塞，还未产生结果时返回 null
        log.debug("结果:{}",future.getNow());

        //nio线程异步获取结果
        future.addListener(new GenericFutureListener<Future<? super String>>() {
            @Override
            public void operationComplete(Future<? super String> future) throws Exception {
                log.debug("结果:{}",future.getNow());
            }
        });


    }
}
